// 扫码处理程序
export const handleScan = {
  // 验证扫码场景
  async validate(request, env) {
    const { sceneId } = await request.json();
    
    const session = await env.DB.prepare(`
      SELECT * FROM target_app_sessions
      WHERE scene_id = ? AND status = 'WAITING'
      AND expired_at > datetime('now')
    `).bind(sceneId).first();
    
    return new Response(JSON.stringify({
      code: 200,
      data: {
        valid: !!session
      }
    }));
  },

  // 更新扫码状态
  async updateStatus(request, env) {
    const { user } = request;
    const { sceneId, status } = await request.json();
    
    // 更新状态
    await env.DB.prepare(`
      UPDATE target_app_sessions
      SET status = ?
      WHERE scene_id = ? AND status = 'WAITING'
      AND expired_at > datetime('now')
    `).bind(status, sceneId).run();
    
    return new Response(JSON.stringify({
      code: 200,
      message: '状态更新成功'
    }));
  },

  // 授权登录
  async authorize(request, env) {
    const { user } = request;
    const { sceneId, accountId } = await request.json();
    
    // 验证账号所有权
    const account = await env.DB.prepare(`
      SELECT a.* 
      FROM accounts a
      JOIN employees e ON a.employee_id = e.id
      WHERE a.id = ? AND (e.phone = ? OR e.email = ?)
    `).bind(accountId, user.value, user.value).first();
    
    if (!account) {
      return new Response(JSON.stringify({
        code: 403,
        message: '无权使用该账号登录'
      }));
    }
    
    // 更新会话状态
    const loginToken = crypto.randomUUID();
    await env.DB.prepare(`
      UPDATE target_app_sessions
      SET status = 'AUTHORIZED',
          account_id = ?,
          login_token = ?
      WHERE scene_id = ? 
      AND status IN ('WAITING', 'SCANNED')
      AND expired_at > datetime('now')
    `).bind(accountId, loginToken, sceneId).run();
    
    // 记录登录日志
    await env.DB.prepare(`
      INSERT INTO login_logs (
        code,
        login_account_id,
        app_id,
        login_type,
        login_platform,
        login_ip,
        login_location,
        login_device_info,
        status,
        created_at
      ) VALUES (?, ?, ?, 'scan', ?, ?, ?, ?, 'success', datetime('now'))
    `).bind(
      crypto.randomUUID(),
      accountId,
      account.app_id,
      user.platform,
      request.headers.get('CF-Connecting-IP'),
      request.headers.get('CF-IPCountry'),
      JSON.stringify(request.headers.get('User-Agent')),
    ).run();
    
    return new Response(JSON.stringify({
      code: 200,
      data: {
        loginToken
      }
    }));
  }
};
